var base64Format = 'data:image/png;base64,';
var energyImage,seamImage,finalImage,imag,inputHeight,inputWidth,resizeOpt,seamEnlarge,urlParam;
var resultsResponse;
var holder = document.getElementById('holder'), tests = {
					filereader : typeof FileReader != 'undefined',
					dnd : 'draggable' in document.createElement('span'),
					formdata : !!window.FormData,
					progress : "upload" in new XMLHttpRequest
				}, support = {
					filereader : document.getElementById('filereader'),
					formdata : document.getElementById('formdata'),
					progress : document.getElementById('progress')
				}, acceptedTypes = {
					'image/png' : true,
					'image/jpeg' : true,
					'image/gif' : true
				}, progress = document.getElementById('uploadprogress'), fileupload = document
						.getElementById('upload');

				"filereader formdata progress".split(' ').forEach(
						function(api) {
							if (tests[api] === false) {
								support[api].className = 'fail';
							} else {
								// FFS. I could have done el.hidden = true, but IE doesn't support
								// hidden, so I tried to create a polyfill that would extend the
								// Element.prototype, but then IE10 doesn't even give me access
								// to the Element object. Brilliant.
								support[api].className = 'hidden';
							}
						});

				function previewfile(file) {
					if (tests.filereader === true
							&& acceptedTypes[file.type] === true) {
						var reader = new FileReader();
						reader.onload = function(event) {
							var image = new Image();
							image.src = event.target.result;
							//image.width = 400; // a fake resize
							//alert(image.width+'px');
							$('#holder').width(image.width+'px');
							holder.appendChild(image);
						};

						reader.readAsDataURL(file);
					} else {
						holder.innerHTML += '_$tUploaded '
								+ file.name
								+ ' '
								+ (file.size ? (file.size / 1024 | 0) + 'K'
										: '');
						console.log(file);
					}
				}
			/*************************************************************************
			 *  Different button associated with images
			 * **********************************************************************/	
				//clear the div portion
				$('#clear').click(function() {
					$('#holder').empty();
					$('#holder').width('400px');
					 $( "#uploadprogress" ).val(0);
					 energyImage = null,seamImage = null,finalImage = null;
					 
					 return false;
				});
				

				$('#submit').click(function() {

					imageFiles = document.getElementById('files').files;
					resizeOpt= document.getElementById("resize").value;
					seamEnlarge = document.getElementById("seamEnlarge").value;
					if(seamEnlarge=='Yes')
					{
					inputHeight = document.getElementById("height").value;
					inputWidth = document.getElementById("width").value;

					}
				else
					{
					inputHeight = document.getElementById("sHeight").value;
					inputWidth = document.getElementById("sWidth").value;
					}
					urlParam="horzNum="+inputHeight+"&vertNum="+inputWidth+"&resize="+resizeOpt
					+"&seamEnlarge="+seamEnlarge;
					// get the number of files
					numFiles = imageFiles.length;
					readfiles(imageFiles);
					
					return false;
				});
				
				$('#energy').click(function() {
					displayImage(energyImage);
					return false;
				});
				
				$('#seam').click(function() {
					displayImage(seamImage);
					return false;
				});
				
				$('#final').click(function() {
					displayImage(finalImage);
					return false;
				});
				$('#saveImage').click(function() {
				 window.location = imag.src.replace('image/png', 'image/octet-stream');
				 return false;
				});
				//display series of images energyImage,seamImage,finalImage
				$('#slideShow').click(function() {
					
					//$.modal("<div><h1>SimpleModal</h1></div>");
					$('#slide1').attr('src',energyImage);
					$('#slide2').attr('src',seamImage);
					$('#slide3').attr('src',finalImage);
					
				$('#features').modal({
					opacity : 40,
					close : true,
					closeHTML:"",
					containerCss : {
						backgroundColor : "white",
						position :'fixed',
						width : 'auto'
					}
				});
				/*$("#features").jshowoff({
					effect : "fade",
					controls : false,
					links : false,
					speed : 3000,
					hoverPause : true
				});*/
				return false;

				});
				
			/*	$('#closeSlide').click(function() {					
					$.modal.close();
					$('#features').hide();
					
				});*/
				/*$(document).ready(function() {
					
				});*/
			
				
				$("#enlarge").children().attr('disabled','disabled');
				// toggle the values
				$("#seamEnlarge").change(function() {
					seamEnlarge = $("#seamEnlarge").val();
					if(seamEnlarge=='Yes')
						{
						inputHeight = document.getElementById("height").value;
						inputWidth = document.getElementById("width").value;
						$("#remove").children().attr('disabled','disabled');
						$("#enlarge").children().attr('disabled','');

						}
					else
						{
						inputHeight = document.getElementById("sHeight").value;
						inputWidth = document.getElementById("sWidth").value;
						$("#enlarge").children().attr('disabled','disabled');
						$("#remove").children().attr('disabled','');
						}
					});
				/**************************************************************************/

				function readfiles(files) {
					//debugger;
					//alert('inside readfiles');
					var formData = tests.formdata ? new FormData() : null;
					for ( var i = 0; i < files.length; i++) {
						if (tests.formdata)
							formData.append('file', files[i]);
						previewfile(files[i]);
					}

					//alert(jspPath);
					// now post a new XHR request
					if (tests.formdata) {
						//alert('inside form data');
						var xhr = new XMLHttpRequest();
						xhr.open('POST', "/Seam-Carve/Main?"+urlParam);
						//xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
						xhr.onload = function() {
							progress.value = progress.innerHTML = 100;
						};

						if (tests.progress) {
							xhr.upload.onprogress = function(event) {
								if (event.lengthComputable) {
									var complete = (event.loaded / event.total
											* 100 | 0);
									progress.value = progress.innerHTML = complete;
									$('#uploadprogress').hide();
								}
							};
						}
						xhr.onreadystatechange = function() {
						   /*get the list of all images and only display final image*/
							if (xhr.readyState == 4 ) {
								//var jsonResponse = JSON.parse(req.responseText);
						    	resultsResponse = xhr.responseText.split(',');
						    	//alert(jsonResponse[0]);
						    	if(resultsResponse.length>2)
						    		{
						    		energyImage=resultsResponse[0];
						    		seamImage =resultsResponse[1]; 
						    		finalImage =resultsResponse[2];
						    		}
						    	else
						    		{
						    		finalImage =resultsResponse[0];
						    		}
						    }
						    	 
						        displayImage(finalImage);
						    
						};
						xhr.send(formData);
					}
				}
				//display image inside the processed image holder
				var displayImage = function (base64Data) {
		             imag = "<img "
		                     + "src='" + "data:image/jpg;base64,"
		                     + base64Data + "' width=400/>";
		 
		            $("#finalHolder").html(imag);
		        };

				if (tests.dnd) {
					holder.ondragover = function() {
						this.className = 'hover';
						return false;
					};
					holder.ondragend = function() {
						this.className = '';
						return false;
					};
					holder.ondrop = function(e) {
						this.className = '';
						e.preventDefault();
						readfiles(e.dataTransfer.files);
					};
				} else {
					fileupload.className = 'hidden';
					fileupload.querySelector('input').onchange = function() {
						readfiles(this.files);
					};
				}
				
			
				
				